package com.example.jiankang;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;

public class HealthDatabaseHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "HealthRecords.db";
    private static final int DATABASE_VERSION = 1;

    public static final String TABLE_HEALTH = "health_records";
    public static final String COLUMN_ID = "_id";
    public static final String COLUMN_DATE = "record_date";
    public static final String COLUMN_WEIGHT = "weight";
    public static final String COLUMN_BLOOD_PRESSURE = "blood_pressure";
    public static final String COLUMN_HEART_RATE = "heart_rate";
    public static final String COLUMN_GLUCOSE = "glucose";

    public HealthDatabaseHelper(@Nullable Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        //创建表SQL
        String CREATE_TABLE = "CREATE TABLE " + TABLE_HEALTH + "("
                + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                + COLUMN_DATE + " TEXT DEFAULT CURRENT_TIMESTAMP, "
                + COLUMN_WEIGHT + " REAL, "
                + COLUMN_BLOOD_PRESSURE + " TEXT, "
                + COLUMN_HEART_RATE + " INTEGER, "
                + COLUMN_GLUCOSE + " REAL)";
        db.execSQL(CREATE_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_HEALTH);
        onCreate(db);
    }

    //插入健康记录
    public long insertRecord(double weight, String bloodPressure, int heartRate, double glucose) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(COLUMN_WEIGHT, weight);
        values.put(COLUMN_BLOOD_PRESSURE, bloodPressure);
        values.put(COLUMN_HEART_RATE, heartRate);
        values.put(COLUMN_GLUCOSE, glucose);
        return db.insert(TABLE_HEALTH, null, values);
    }

    //获取最新一条记录
    public Cursor getLatestRecord() {
        SQLiteDatabase db = this.getReadableDatabase();
        return db.query(
                TABLE_HEALTH,
                null,
                null,
                null,
                null,
                null,
                COLUMN_DATE + " DESC",
                "1" // 只获取一条
        );
    }
}